# snake.py
import pygame
from constants import WIDTH, HEIGHT, BLOCK_SIZE, GREEN, screen, snake_sprites

# 定义精灵图中的各个部分的像素值，40像素
SPRITE_SIZE = BLOCK_SIZE * 2


class Snake:
    def __init__(self):
        self.body = [(WIDTH // 2, HEIGHT // 2), (WIDTH // 2 - BLOCK_SIZE, HEIGHT // 2), (WIDTH // 2 - BLOCK_SIZE * 2, HEIGHT // 2)]  # 初始位置
        self.direction = "RIGHT"  # 初始方向
        self.grow = False  # 是否增长

    def move(self):
        # 计算新头部位置
        head_x, head_y = self.body[0]
        if self.direction == "UP":
            head_y -= BLOCK_SIZE
        elif self.direction == "DOWN":
            head_y += BLOCK_SIZE
        elif self.direction == "LEFT":
            head_x -= BLOCK_SIZE
        elif self.direction == "RIGHT":
            head_x += BLOCK_SIZE

        # 插入新头部并移除尾部（除非需要增长）
        self.body.insert(0, (head_x, head_y))
        if not self.grow:
            self.body.pop()
        else:
            self.grow = False

    def change_direction(self, new_dir):
        # 防止反向移动
        if (
            (new_dir == "UP" and self.direction != "DOWN")
            or (new_dir == "DOWN" and self.direction != "UP")
            or (new_dir == "LEFT" and self.direction != "RIGHT")
            or (new_dir == "RIGHT" and self.direction != "LEFT")
        ):
            self.direction = new_dir

    def check_collision(self):
        """检查蛇是否撞墙或撞到自己"""
        head = self.body[0]
        # 检查是否撞墙
        if head[0] < 0 or head[0] >= WIDTH or head[1] < 0 or head[1] >= HEIGHT:
            return True
        # 检查是否撞到自己
        if head in self.body[1:]:
            return True
        return False

    def check_eat_food(self, food_position):
        """检查蛇是否吃到食物"""
        return self.body[0] == food_position

    def draw(self):
        if snake_sprites and len(self.body) > 0:
            # 绘制蛇身（从尾部到头部）
            for i in range(len(self.body) - 1, -1, -1):
                segment = self.body[i]

                if i == 0:  # 蛇头
                    sprite = snake_sprites["head"][self.direction]
                    screen.blit(sprite, segment)

                elif i == len(self.body) - 1:  # 蛇尾
                    prev_segment = self.body[i - 1]
                    if prev_segment[0] > segment[0]:
                        direction = "LEFT"
                    elif prev_segment[0] < segment[0]:
                        direction = "RIGHT"
                    elif prev_segment[1] > segment[1]:
                        direction = "UP"
                    else:
                        direction = "DOWN"
                    sprite = snake_sprites["tail"][direction]
                    screen.blit(sprite, segment)

                else:  # 中间段
                    prev_segment = self.body[i - 1]
                    next_segment = self.body[i + 1]

                    if prev_segment[0] == next_segment[0]:  # 垂直
                        sprite = snake_sprites["straight"]["H"]
                    elif prev_segment[1] == next_segment[1]:  # 水平
                        sprite = snake_sprites["straight"]["V"]
                    else:  # 弯段
                        if (prev_segment[0] < segment[0] and next_segment[1] < segment[1]) or (prev_segment[1] < segment[1] and next_segment[0] < segment[0]):
                            sprite = snake_sprites["corner"]["TL"]
                        elif (prev_segment[0] > segment[0] and next_segment[1] < segment[1]) or (prev_segment[1] < segment[1] and next_segment[0] > segment[0]):
                            sprite = snake_sprites["corner"]["TR"]
                        elif (prev_segment[0] < segment[0] and next_segment[1] > segment[1]) or (prev_segment[1] > segment[1] and next_segment[0] < segment[0]):
                            sprite = snake_sprites["corner"]["BL"]
                        else:
                            sprite = snake_sprites["corner"]["BR"]
                    screen.blit(sprite, segment)
        else:
            # 如果精灵图加载失败，使用默认方块绘制
            for segment in self.body:
                pygame.draw.rect(screen, GREEN, pygame.Rect(segment[0], segment[1], BLOCK_SIZE, BLOCK_SIZE))
